"""
套接字编程 - TCP服务器
池化技术 - 空间换时间
线程池 - 提前创建一个容器在容器中放置多个线程对象，需要使用线程的时候不需要创建和释放，
仅仅是向容器借还线程对象，从而减少创建和释放线程的开销
"""
import os

from concurrent.futures import ProcessPoolExecutor
from datetime import datetime
from socket import socket
from threading import Thread



# class ClientHandler(Thread):

#     def __init__(self, client):
#         self.client = client
#         super().__init__(daemon=True)

#     def run(self):
#         file_size = os.path.getsize('guido.jpg')
#         self.client.send(str(file_size).encode())
#         with open('guido.jpg', 'rb') as file:
#             for data in iter(lambda: file.read(4096), b''):
#                 self.client.send(data)


def handle_request(client):
    file_size = os.path.getsize('guido.jpg')
    client.send(str(file_size).encode())
    with open('guido.jpg', 'rb') as file:
        for data in iter(lambda: file.read(4096), b''):
            client.send(data)


pool = ProcessPoolExecutor(16)
server = socket()
server.bind(('127.0.0.1', 6789))
server.listen(512)
try:
    while True:
        try:
            client, (ip, port) = server.accept()
            print(f'客户端IP地址: {ip}, 端口: {port}')
            pool.submit(handle_request, client)
        except Exception as ex:
            print(type(ex), ex)
except KeyboardInterrupt:
    server.close()
